package net.hn.hnms.biz.indicator.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import net.hn.hnms.biz.indicator.dao.SysIndicatorMapper;
import net.hn.hnms.biz.indicator.dao.SysIndicatorRolesMapper;
import net.hn.hnms.biz.indicator.entity.GasModelValueDTO;
import net.hn.hnms.biz.indicator.entity.SysIndicator;
import net.hn.hnms.biz.indicator.entity.SysIndicatorRoles;
import net.hn.hnms.sys.common.core.exception.ServiceException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

/**
 * @author 智呈物联 nzw
 * @date 2022/8/24
 */
@Service
public class SysIndicatorService {

    SysIndicatorMapper sysIndicatorMapper;

    SysIndicatorRolesMapper sysIndicatorRolesMapper;

    SysIndicatorRolesMapper indicatorRolesService;

    @Autowired
    public void setSysIndicatorRolesMapper(SysIndicatorRolesMapper sysIndicatorRolesMapper) {
        this.sysIndicatorRolesMapper = sysIndicatorRolesMapper;
    }

    @Autowired
    public void setSysIndicatorMapper(SysIndicatorMapper sysIndicatorMapper) {
        this.sysIndicatorMapper = sysIndicatorMapper;
    }

    @Autowired
    public void setIndicatorRolesService(SysIndicatorRolesMapper indicatorRolesService) {
        this.indicatorRolesService = indicatorRolesService;
    }


    private static int lenthItempart = 4;

    public void processWeight(List<GasModelValueDTO> modelList, String firstCode) {
        Map<String, String> weight = putWeight(firstCode);
        modelList.forEach(
                item -> item.setProblemStr(
                        BigDecimal.valueOf(NumberUtil.mul(
                                Double.valueOf(item.getProblemStr()),
                                Double.valueOf(weight.get(item.getIndicatorThirdLevelCode()))
                        )).setScale(lenthItempart, BigDecimal.ROUND_HALF_UP) + ""
                )
        );
    }

    /**
     * 返回一个 key：三级code  value：二级权重
     *
     * @param firstCode
     * @return
     */
    public Map<String, String> putWeight(String firstCode) {
        List<SysIndicator> indicators = sysIndicatorMapper.findAllByIndicatorFirstLevelCode(firstCode);
        ConcurrentMap<String, String> concurrentMap = indicators.stream()
                .filter(item -> StrUtil.isBlank(item.getIndicatorThirdLevelCode()))
                .collect(Collectors.toConcurrentMap(
                                item -> item.getIndicatorSecondLevelCode(),
                                item -> item.getIndicatorWeightValue()
                        )
                );
        ConcurrentMap<String, String> result = indicators.stream()
                .filter(item -> StrUtil.isNotBlank(item.getIndicatorThirdLevelCode()))
                .collect(Collectors.toConcurrentMap(
                                item -> item.getIndicatorThirdLevelCode(),
                                item -> concurrentMap.get(item.getIndicatorSecondLevelCode())
                        )
                );

        return result;
    }

    public List<SysIndicator> list() {
        return sysIndicatorMapper.findAll();
    }

    public List<SysIndicatorRoles> rolesByIndicatorId(Long id) {
        List<SysIndicatorRoles> sysIndicatorRoles = indicatorRolesService.queryAllByIndicatorId(id);
        return sysIndicatorRoles;
    }


    public boolean deleteRole(Long id) {
        sysIndicatorRolesMapper.deleteById(id);
        return true;
    }

    public boolean saveOrUpdate(SysIndicatorRoles indicatorRoles) {
        sysIndicatorRolesMapper.save(indicatorRoles);
        return true;
    }

    public Map<String, Object> getInfo(Long id) {
        SysIndicator byId = sysIndicatorMapper.findById(id).get();
        List<SysIndicatorRoles> collect = sysIndicatorRolesMapper.queryAllByIndicatorId(id);
        byId.setRoles(collect);
        Map<String, Object> map = new HashMap<>();
        map.put("content", byId);
        map.put("totalElements", 1);
        return map;
    }

    public SysIndicator selectById(Long id) {
        return sysIndicatorMapper.findById(id).get();
    }

    public SysIndicator saveInfo(SysIndicator entity) {
        entity.setCreateTime(LocalDateTime.now());
        String thirdCode = entity.getIndicatorThirdLevelCode();
        String secondCode = entity.getIndicatorSecondLevelCode();
        String firstCode = entity.getIndicatorFirstLevelCode();
        String indicatorWeightValue = entity.getIndicatorWeightValue();
        if ("".equals(indicatorWeightValue)) {
            entity.setIndicatorWeightValue("0.0");
        }
        //先判断是哪一级
        if (StringUtils.isNotBlank(thirdCode)) {
            throw new ServiceException("最多三级！");
        }
        if (StringUtils.isNotBlank(secondCode)) {
            //生成三级code
            SysIndicator one = sysIndicatorMapper.queryMaxThiredCode(secondCode);
            String third = one.getIndicatorThirdLevelCode();
            if (StringUtils.isBlank(third)) {
                third = secondCode + "00";
            }
            entity.setIndicatorFirstLevelCode(one.getIndicatorFirstLevelCode());
            entity.setIndicatorThirdLevelCode(Integer.valueOf(third) + 1 + "");
            entity.setIndicatorThirdLevelName(entity.getIndicatorSecondLevelName());
            entity.setIndicatorSecondLevelName(one.getIndicatorSecondLevelName());
            entity.setIndicatorFirstLevelName(one.getIndicatorFirstLevelName());
            return sysIndicatorMapper.save(entity);
        }
        if (StringUtils.isNotBlank(firstCode)) {
            //生成二级code
            SysIndicator one = sysIndicatorMapper.queryMaxSecondCode(firstCode);
            String second = one.getIndicatorSecondLevelCode();
            if (StringUtils.isBlank(second)) {
                second = firstCode + "00";
            }
            entity.setIndicatorSecondLevelCode(Integer.valueOf(second) + 1 + "");
            entity.setIndicatorFirstLevelName(one.getIndicatorFirstLevelName());
            return sysIndicatorMapper.save(entity);
        }
        //生成一级code
        String first = sysIndicatorMapper.queryMaxFirstCode();
        if ("".equals(first)) {
            first = "09";
        } else {
            first = Integer.valueOf(first) + 9 + "";
        }
        entity.setIndicatorFirstLevelCode(Integer.valueOf(first) + 1 + "");
        entity.setIndicatorFirstLevelName(entity.getIndicatorSecondLevelName());
        entity.setIndicatorSecondLevelName(null);
        return sysIndicatorMapper.save(entity);
    }

    public SysIndicator updateInfo(SysIndicator entity) {
//        List<SysIndicator> history=sysIndicatorMapper.selectHistory(entity.getId());
//        entity.setCreateTime(history.get(0).getCreateTime());
//        history.add(entity);
//        return sysIndicatorMapper.saveBatch(history);
        SysIndicator byId = sysIndicatorMapper.findById(entity.getId()).get();
        entity.setCreateTime(byId.getCreateTime());
        if (StrUtil.isBlank(byId.getIndicatorSecondLevelCode())) {
            //修改一级的
            entity.setIndicatorFirstLevelName(entity.getIndicatorSecondLevelName());
            //修改为null 是不会去修改这个字段
            entity.setIndicatorSecondLevelName(null);
            return sysIndicatorMapper.save(entity);
        }
        if (StrUtil.isNotBlank(byId.getIndicatorThirdLevelCode())) {
            //修改三级的
            entity.setIndicatorThirdLevelName(entity.getIndicatorSecondLevelName());
            entity.setIndicatorSecondLevelName(null);
            entity.setIndicatorFirstLevelName(null);
            return sysIndicatorMapper.save(entity);
        }
        //修改二级不做修改
        entity.setIndicatorFirstLevelName(null);
        return sysIndicatorMapper.save(entity);
    }

    public boolean removeById(Long id) {
        // 判断是否有子集数据，有的话提示先删除子集
        Optional<SysIndicator> byId = sysIndicatorMapper.findById(id);
        if (!byId.isPresent()) {
            throw new ServiceException("数据不存在！");
        }
        SysIndicator sysIndicator = byId.get();
        // 一级
        if (StringUtils.isBlank(sysIndicator.getIndicatorSecondLevelCode())) {
            if (sysIndicatorMapper.findAllByIndicatorFirstLevelCode(byId.get().getIndicatorFirstLevelCode()).size() > 1) {
                throw new ServiceException("请先删除子节点！");
            }
        } else if (StringUtils.isBlank(sysIndicator.getIndicatorThirdLevelCode())) {
            // 二级
            if (sysIndicatorMapper.findAllByIndicatorSecondLevelCode(byId.get().getIndicatorSecondLevelCode()).size() > 1) {
                throw new ServiceException("请先删除子节点！");
            }
        }
        sysIndicatorMapper.deleteById(id);
        return true;
    }


}
